package cn.sonui.onlinechat.api;

import cn.sonui.onlinechat.bean.InteractiveData;
import cn.sonui.onlinechat.bean.MessageInfo;
import cn.sonui.onlinechat.bean.UserInfo;
import cn.sonui.onlinechat.utils.MD5;
import cn.sonui.onlinechat.utils.MessageHandle;
import cn.sonui.onlinechat.utils.MessageList;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static cn.sonui.onlinechat.utils.OnlineChat.*;

@RestController
@ServerEndpoint("/chat-room")
public class ChatRoomServerEndpoint {
    private static final Logger log = LoggerFactory.getLogger(ChatRoomServerEndpoint.class);
    @OnOpen
    public void openSession(Session session) {
        log.info("New client,socket id: " + session.getId());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info(String.format("client[%s], content[%s]", session.getId(), message));
        InteractiveData data = JSON.parseObject(message, InteractiveData.class);
        InteractiveData sendData = new InteractiveData();

        MessageHandle messageHandle = new MessageHandle(sendData);

        switch (data.getCode()) {
            case 1 -> {
                //session绑定
                String token = data.getToken();
                int start = token.indexOf("token");
                start += "token".length() + 1;//去掉名和等号
                int end = token.indexOf(";", start);
                end = end == -1 ? token.length() : end;
                token = token.substring(start, end);
                Integer res = messageHandle.bindWebSockeet(session, token);
                if (res == 1) {
                    sendData.setCode(16);
                    sendData.setMsg("bind ok");
                } else if (res == 2) {
                    sendData.setCode(-1);
                    sendData.setMsg("no token");
                }
            }
            case 2 -> {
                //ss
            }
            default -> {
                sendData.setCode(17);
                sendData.setMsg("no this code");
            }
        }
        session.getAsyncRemote().sendText(JSON.toJSONString(sendData, SerializerFeature.BrowserCompatible));
    }

    @OnClose
    public void onClose(Session session) {
        //当前的Session 移除
        //LIVING_SESSIONS_CACHE.remove(username);
        //并且通知其他人当前用户已经离开聊天室了
        //sendMessageAll("用户[" + username + "] 已经离开聊天室了！");
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }

    @PostMapping("/chat-room/api/send")
    public Map<String, Object> sender(
            @RequestParam(name = "msg") String msg,
            @RequestParam(name = "roomId") Integer roomId,
            @RequestParam(name = "userId", required = false) Integer userId, //当roomI为-1时表私聊从此获取接收对象
            HttpServletRequest request
    ) throws Exception {
        log.info(msg);
        HttpSession session = request.getSession();
        Integer uid = (Integer) session.getAttribute("uid");
        Map<String, Object> ret = new HashMap<>();

        if (roomId == -1 && userId == null) {
            ret.put("code", -1);
            ret.put("msg", "参数错误");
            return ret;
        }
        MessageInfo msgTemp = new MessageInfo();
        msgTemp.setSender(uid);
        msgTemp.setMessage(msg);
        msgTemp.setRecipient(roomId != -1 ? roomId : userId);
        msgTemp.setType(roomId != -1 ? 1 : 2);//1群消息 2私聊
        Integer mid = msgCache.addMessage(msgTemp);
        MessageHandle msgHandle = new MessageHandle();

        ret.put("code", "1");
        ret.put("msgId", mid);
        ret.put("toNum", msgHandle.sendMessage(roomId, msgTemp));
        ret.put("msgTag", MD5.getMD5Code(msg));
        return ret;
    }

    @PostMapping("/chat-room/api/room")
    public Map<String, Object> roomExec(
            @RequestParam(name = "code") Integer code,
            @RequestParam(name = "roomId") Integer roomId,
            @RequestParam(name = "roomName", required = false) Integer roomName, //当code为4时从此获取房间名
            HttpServletRequest request
    ) {
        HttpSession session = request.getSession();
        Integer uid = (Integer) session.getAttribute("uid");
        Map<String, Object> ret = new HashMap<>();
        MessageInfo msgTemp = new MessageInfo();
        switch (code){
            case 3:
                //加入聊天室
                break;
            case 4:
                //退出聊天室
                break;
            case 5:
                //创建聊天室
                break;
            default:
                ret.put("code", -1);
                ret.put("msg", "参数错误");
        }
        return ret;
    }
}